#ifndef LIBTORRENT_PEER_CONNECTION_H
#define LIBTORRENT_PEER_CONNECTION_H

#include "bitfield.h"
#include "service.h"
#include "socket_base.h"
#include "peer_connection_sub.h"
#include "peer.h"

namespace torrent {

class Download;

class PeerConnection : public SocketBase, public Service {
public:
	friend class Sub;
	PeerConnection();
	~PeerConnection();

	void set(int fd, const Peer& p, Download* d);

	bool chokeDelayed();

	const BitField& bitfield() const { return m_bitfield; }

	const Peer& peer() const { return m_peer; }

	Sub& up() { return m_up; }
	Sub& down() { return m_down; }

	virtual void read();
	virtual void write();
	virtual void except();

	virtual int fd();

private:

	// Send a msg to the buffer.
	void bufCmd(Protocol cmd, unsigned int length, unsigned int send = 0);

	enum {
		SERVICE_KEEP_ALIVE = 0x2000,
		SERVICE_SEND_CHOKE,
		SERVICE_INCOMING_PIECE
	};

	int m_fd;
	bool m_shutdown;

	Peer m_peer;
	Download* m_download;

	BitField m_bitfield;

	bool m_sendChoked;
	bool m_sendInterested;
	bool m_sendBitfield;

	Timer m_lastChoked;
	Timer m_lastMsg;

	Sub m_up;
	Sub m_down;
};

} // namespace torrent

#endif // LIBTORRENT_PEER_CONNECTION_H
